﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarolLib.Control;
using System.Xml;
using System.Collections;
using DispatchAssist.Service;
using System.Threading;
using CarolLib;
using DispatchAssist.Model;
using System.Configuration;
using System.Web.Services.Protocols;
using System.Web.Services;
using DispatchAssist.BusinessLogical.BLL;
using DispatchAssist.BusinessLogical.Model;

namespace DispatchAssist.AppHost
{
    [ModuleContract("2F3CB49B-3B55-4C63-BC30-28857E84FAFA", "预警管理", "预警信息提示")]
    public partial class MeteoMsgAlert : MdiUserControl
    {
        #region Members

        AlertMessageGetterService service = new AlertMessageGetterService();
        RuleManagerService rule_service = new RuleManagerService();
        List<DispatchAssist.Service.InfoAirport> airportlst = new List<DispatchAssist.Service.InfoAirport>();
        int tspan = int.Parse(ConfigurationManager.AppSettings["tspan"]);
        ClientMessageInfo clientMInfo = new ClientMessageInfo();
        delegate void FunDelegate();
        WaitForm wff = new WaitForm();
        private List<NormalAlertInfo> normalList = null;
        public List<NormalAlertInfo> NormalList
        {
            get
            {
                return normalList;
            }
            set
            {
                normalList = value;
            }

        }


        //验证登陆状态
        private bool IsExists = false;

        static readonly string WarnFormatEst = "[{0}]: 【{7}】{1}机场发生{8}，作为{9}影响航班{2}{3}({4}---{5})，航班预计起飞时间:{10},告警内容：{6}";
        static readonly string WarnFormatReal = "[{0}]: 【{7}】{1}机场发生{8}，作为{9}影响航班{2}{3}({4}---{5})，航班实际起飞时间:{10},告警内容：{6}";

        static readonly string WarnFormat = "[{0}]: 【{7}】{1}机场发生{8}，作为{9}影响航班{2}{3}({4}---{5})，告警内容：{6}";
        static readonly string SMSWarnFormat = "[{0}]: 【{1}】{2}机场发生{3}，影响{4}个航班，告警内容：{5}";

        private static readonly string UnConfimFormat = "{0}发送了委托请求,请求你代理席位【{1}】";

        private static readonly string AgreeFormat = "席位【{0}】同意了你的委托请求,你在退出系统后,预警信息即发送到委托席位";

        private static readonly string RejectFormat = "席位【{0}】拒绝了你的委托请求!";

        private static readonly string UnDelegateFormat = "席位【{0}】重新登录了,跟你的委托关系已解除";


        private readonly object locker = new object();

        #endregion

        #region Ctor.

        public MeteoMsgAlert()
            : base()
        {
            InitializeComponent();
        }

        public MeteoMsgAlert(XmlNode xn)
            : this()
        {
        }

        #endregion

        #region MdiUserControl Members

        public override void Unload()
        {
            this.timerMainTask.Enabled = false;

            base.Unload();
            AlertContext.Dic_Prompt.Clear();
            AlertContext.Dic_Acars.Clear();
            AlertContext.Dic_Sms.Clear();
            AlertContext.Dic_Bubble.Clear();

            AlertContext.oldpromptList = null;
            AlertContext.oldbubbleList = null;
            AlertContext.oldmanualacarsList = null;
            AlertContext.oldmanualsmsList = null;

            ExistRelationIDs = null;
        }

        public override void Onload()
        {
            base.Onload();

            ExistRelationIDs = new List<Guid>();

            //service.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();

            // service.GetJsonAlerMessageCompleted += new GetJsonAlerMessageCompletedEventHandler(service_GetJsonAlerMessageCompleted);

            service.GetJsonAlerMessageBySeatListCompleted += new GetJsonAlerMessageBySeatListCompletedEventHandler(service_GetJsonAlerMessageCompleted);

            airportlst = rule_service.GetAllAirports().ToList<DispatchAssist.Service.InfoAirport>();

            richAlertMsg.Text = "";
            SysGlobal.oldNormalAlertInfoList = null;
            this.timerMainTask.Interval = tspan;
            this.timerMainTask.Enabled = true;


            timPromptAlert.Interval = 1;
            timPromptAlert.Enabled = true;

            timManualSendAcrarsAlert.Interval = 1;
            timManualSendAcrarsAlert.Enabled = true;

            timManualSendSMSAlert.Interval = 1;
            timManualSendSMSAlert.Enabled = true;

            //DisposeMessagerGetter();


        }

        #endregion

        #region Methods.

        public override bool CommonFun()
        {
            if ((AlertContext.Dic_Acars != null && AlertContext.Dic_Acars.Count > 0) || (AlertContext.Dic_Bubble != null && AlertContext.Dic_Bubble.Count > 0) || (AlertContext.Dic_Prompt != null && AlertContext.Dic_Prompt.Count > 0) || (AlertContext.Dic_Sms != null && AlertContext.Dic_Sms.Count > 0))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private string GetAlertActionNameByFlag(int Flag)
        {
            string str = "";
            switch (Flag)
            {
                case (int)Enums.AlertActionFlag.BubbleAlert:
                    str = "冒泡提示";
                    break;
                case (int)Enums.AlertActionFlag.PromptAlert:
                    str = "弹框提示";
                    break;
                case (int)Enums.AlertActionFlag.ManualSendAcrarsAlert:
                    str = "手动发送Acars报";
                    break;
                case (int)Enums.AlertActionFlag.ManualSendSMSAlert:
                    str = "手动发送短信";
                    break;
                case (int)(Enums.AlertActionFlag.AutoSendAcarsAlert | Enums.AlertActionFlag.ConfirmAcars):
                    str = "自动发送Acars报";
                    break;
                case (int)(Enums.AlertActionFlag.AutoSendSMSAlert | Enums.AlertActionFlag.ConfirmSMS):
                    str = "自动发送短信";
                    break;
                default:
                    str = "无";
                    break;

            }
            return str;
        }


        private string GetCode4ByCode3(string code3)
        {
            DispatchAssist.Service.InfoAirport info = airportlst.Find(s => s.Code3 == code3);

            return (info == null) ? "" : info.Code4;
        }

        private void DisposeMessagerGetter()
        {
            try
            {
                //异步
                //service.GetJsonAlerMessageAsync(AuthContext.Current.Credentials[0].SeatID.ToString(), DateTime.Now.Ticks);

                service.DASoapHeaderValue = AuthContext.Current.GetSoapHeader();

                service.GetJsonAlerMessageBySeatListAsync();

                timerMainTask.Enabled = false;

                //同步
                //string json = service.GetJsonAlerMessage(AuthContext.Current.Credentials[0].SeatID.ToString());
                //HandleJsonResult(json);

            }
            catch (SoapHeaderException soapEx)
            {
                MessageBox.Show("SoapHeader Error : " + soapEx.Message);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error : " + ex.Message);
            }
        }

        private void PromptAlertMethod()
        {


            ClientMessageInfo cminfo = clientMInfo.GetAlertMessageByAlertAction((int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.PromptAlert);
            if (cminfo.NormalAlertList != null && cminfo.NormalAlertList.Count > 0)
            {
                List<NormalAlertInfo> newpromptlst = new List<NormalAlertInfo>();
                if (AlertContext.oldpromptList == null)
                {
                    newpromptlst = cminfo.NormalAlertList;
                    AlertContext.oldpromptList = cminfo.NormalAlertList;
                }
                else
                {
                    newpromptlst = getNewAlertInfos(AlertContext.oldpromptList, cminfo.NormalAlertList);
                    if (newpromptlst != null && newpromptlst.Count > 0)
                    {
                        AlertContext.oldpromptList.AddRange(newpromptlst);
                    }
                }

                if (newpromptlst != null && newpromptlst.Count > 0)
                {

                    var groups = newpromptlst.GroupBy(a => a.WarnMsg);

                    foreach (var group in groups)
                    {
                        //group.ToList<NormalAlertInfo>();

                        if (!AlertContext.Dic_Prompt.ContainsKey(group.Key))
                        {
                            frmPromptAlert frm_Prompt = new frmPromptAlert(group.ToList<NormalAlertInfo>());
                            frm_Prompt.wjs();
                            //frm   _Prompt.Hide();



                            AlertContext.Dic_Prompt.Add(group.Key, frm_Prompt);
                        }
                        else
                        {
                            frmPromptAlert frm;
                            AlertContext.Dic_Prompt.TryGetValue(group.Key, out frm);

                            List<NormalAlertInfo> newlst = getNewAlertInfos(frm.alertinfoLst, group.ToList<NormalAlertInfo>());
                            if (newlst != null && newlst.Count > 0)
                            {
                                for (int i = newlst.Count - 1; i >= 0; i--)
                                {
                                    ucPromptAlert ucprompt = new ucPromptAlert(newlst[i]);
                                    ucprompt.Dock = DockStyle.Top;
                                    frm.Controls.Add(ucprompt);
                                }
                            }
                        }
                    }
                }
            }
            //return "suc";

        }

        private void BubbleAlertMethod()
        {
            ClientMessageInfo cminfo_BubbleAlert = clientMInfo.GetAlertMessageByAlertAction((int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.BubbleAlert);
            if (cminfo_BubbleAlert.NormalAlertList != null && cminfo_BubbleAlert.NormalAlertList.Count > 0)
            {
                // List<NormalAlertInfo> newbubblelst = getNewAlertInfos(SysGlobal.oldNormalAlertInfoList, cminfo_BubbleAlert.NormalAlertList);

                List<NormalAlertInfo> newbubblelst = new List<NormalAlertInfo>();
                if (AlertContext.oldbubbleList == null)
                {
                    newbubblelst = cminfo_BubbleAlert.NormalAlertList;
                    AlertContext.oldbubbleList = cminfo_BubbleAlert.NormalAlertList;
                }
                else
                {
                    newbubblelst = getNewAlertInfos(AlertContext.oldbubbleList, cminfo_BubbleAlert.NormalAlertList);
                    if (newbubblelst != null && newbubblelst.Count > 0)
                    {
                        AlertContext.oldbubbleList.AddRange(newbubblelst);
                    }
                }

                if (newbubblelst != null && newbubblelst.Count > 0)
                {

                    foreach (NormalAlertInfo ninfo in newbubblelst)
                    {
                        if (!AlertContext.Dic_Bubble.ContainsKey(ninfo.AlertID.ToString()))
                        {
                            frmBubbleAlert bf = new frmBubbleAlert(ninfo, this);
                            bf.ScrollShow();
                            AlertContext.Dic_Bubble.Add(ninfo.AlertID.ToString(), bf);
                        }
                    }

                }
            }


        }


        private void ManualSendAcrarsAlertMethod()
        {
            ClientMessageInfo cminfo_ManualSendAcrarsAlert = clientMInfo.GetAlertMessageByAlertAction((int)DispatchAssist.BusinessLogical.Model.Enums.AlertActionFlag.ManualSendAcrarsAlert);
            if (cminfo_ManualSendAcrarsAlert.NormalAlertList != null && cminfo_ManualSendAcrarsAlert.NormalAlertList.Count > 0)
            {

                //List<NormalAlertInfo> newmanualacarslst = getNewAlertInfos(SysGlobal.oldNormalAlertInfoList, cminfo_ManualSendAcrarsAlert.NormalAlertList);
                List<NormalAlertInfo> newmanualacarslst = new List<NormalAlertInfo>();
                if (AlertContext.oldmanualacarsList == null)
                {
                    newmanualacarslst = cminfo_ManualSendAcrarsAlert.NormalAlertList;
                    AlertContext.oldmanualacarsList = cminfo_ManualSendAcrarsAlert.NormalAlertList;
                }
                else
                {
                    newmanualacarslst = getNewAlertInfos(AlertContext.oldmanualacarsList, cminfo_ManualSendAcrarsAlert.NormalAlertList);
                    if (newmanualacarslst != null && newmanualacarslst.Count > 0)
                    {
                        AlertContext.oldmanualacarsList.AddRange(newmanualacarslst);
                    }
                }
                if (newmanualacarslst != null && newmanualacarslst.Count > 0)
                {

                    foreach (NormalAlertInfo nainfo in newmanualacarslst)
                    {
                        if (!AlertContext.Dic_Acars.ContainsKey(nainfo.AlertID.ToString()))
                        {
                            frmManualSendAcrarsAlert frm_ACARS = new frmManualSendAcrarsAlert(nainfo, this);
                            //frm_ACARS.Show();
                            frm_ACARS.wjs();
                            AlertContext.Dic_Acars.Add(nainfo.AlertID.ToString(), frm_ACARS);
                        }
                    }

                }
            }


        }
        private void ManualSendSMSAlertMethod()
        {

            ClientMessageInfo cminfo_ManualSendSMSAlert = clientMInfo.GetAlertMessageByAlertAction((int)Enums.AlertActionFlag.ManualSendSMSAlert);
            if (cminfo_ManualSendSMSAlert.SMSAlertList != null && cminfo_ManualSendSMSAlert.SMSAlertList.Count > 0)
            {

                //List<SMSAlertAllInfo> newmanualsmslst = getNewAlertSMSInfos(SysGlobal.oldSMSAlertAllInfoList, cminfo_ManualSendSMSAlert.SMSAlertList);
                List<SMSAlertAllInfo> newmanualsmslst = new List<SMSAlertAllInfo>();
                if (AlertContext.oldmanualsmsList == null)
                {
                    newmanualsmslst = cminfo_ManualSendSMSAlert.SMSAlertList;
                    AlertContext.oldmanualsmsList = cminfo_ManualSendSMSAlert.SMSAlertList;
                }
                else
                {
                    newmanualsmslst = getNewAlertSMSInfos(AlertContext.oldmanualsmsList, cminfo_ManualSendSMSAlert.SMSAlertList);
                    if (newmanualsmslst != null && newmanualsmslst.Count > 0)
                    {
                        AlertContext.oldmanualsmsList.AddRange(newmanualsmslst);
                    }
                }
                if (newmanualsmslst != null && newmanualsmslst.Count > 0)
                {

                    foreach (SMSAlertAllInfo smsAlertInfo in newmanualsmslst)
                    {
                        if (!AlertContext.Dic_Sms.ContainsKey(smsAlertInfo.SMSAlertID.ToString()))
                        {
                            frmManualSendSMSAlert frm_SMS = new frmManualSendSMSAlert(smsAlertInfo);
                            //frm_SMS.Show();
                            frm_SMS.wjs();
                            AlertContext.Dic_Sms.Add(smsAlertInfo.SMSAlertID.ToString(), frm_SMS);
                        }

                    }
                }
            }



        }
        private void HandleJsonResult(string jsonStr)
        {
            clientMInfo = JsonSerializeHelper.DataContractJsonDeserializeByJNet<ClientMessageInfo>(jsonStr);
            List<NormalAlertInfo> lst = clientMInfo.NormalAlertList;
            List<SMSAlertAllInfo> lst_SMS = clientMInfo.SMSAlertList;

            //验证登陆状态
            ValidateLoginStatus(clientMInfo.SeatLoginList);

            //更新委托信息
            ValidateDelegateSeats(clientMInfo.RelationSeats);

            List<NormalAlertInfo> displayNewAlertInfos = new List<NormalAlertInfo>();
            if (SysGlobal.oldNormalAlertInfoList == null)
            {
                displayNewAlertInfos = lst;
                SysGlobal.oldNormalAlertInfoList = lst;
            }
            else
            {
                displayNewAlertInfos = getNewAlertInfos(SysGlobal.oldNormalAlertInfoList, lst);
                if (displayNewAlertInfos != null && displayNewAlertInfos.Count > 0)
                {

                    SysGlobal.oldNormalAlertInfoList.AddRange(displayNewAlertInfos);
                }
            }

            InsertAlertMsgTextToControl(displayNewAlertInfos);

            List<SMSAlertAllInfo> displayNewAlertSMSInfos = new List<SMSAlertAllInfo>();
            if (SysGlobal.oldSMSAlertAllInfoList == null)
            {
                displayNewAlertSMSInfos = lst_SMS;
                SysGlobal.oldSMSAlertAllInfoList = lst_SMS;
            }
            else
            {
                displayNewAlertSMSInfos = getNewAlertSMSInfos(SysGlobal.oldSMSAlertAllInfoList, lst_SMS);
                if (displayNewAlertSMSInfos != null && displayNewAlertSMSInfos.Count > 0)
                {

                    SysGlobal.oldSMSAlertAllInfoList.AddRange(displayNewAlertSMSInfos);
                }
            }

            InsertAlertSMSMsgTextToControl(displayNewAlertSMSInfos);
            //wff = new WaitForm();
            //wjs(wff);

            DisposeAlertProcess();
            #region BubbleAlert
            BubbleAlertMethod();
            #endregion
            //wff.StartPosition = FormStartPosition.CenterParent;
            //wff.ShowDialog();



        }
        public void wjs(WaitForm wf)
        {
            FunDelegate funDelegate = new FunDelegate(DisposeAlertProcess);

            /*========================================================
             * 使用this.BeginInvoke方法
             * （也可以使用this.Invoke()方法）
            ========================================================*/

            // this.BeginInvoke(被调用的方法的委托，要传递的参数[Object数组])


            IAsyncResult aResult = funDelegate.BeginInvoke(callbackm, wf);

            // 用于等待异步操作完成(-1表示无限期等待)
            //aResult.AsyncWaitHandle.WaitOne(0);

            //// 使用this.EndInvoke方法获得返回值
            //string str = (string)this.EndInvoke(aResult);
            //MessageBox.Show(str.ToString());
            //addPromptAlertControls();


        }

        private void callbackm(IAsyncResult result)
        {
            if (result.IsCompleted)
            {
                //((WaitForm)result.AsyncState).Hide(); ;
            }

        }
        private void DisposeAlertProcess()
        {
            #region PromptAlert
            //Thread th = new Thread(PromptAlertMethod);
            //th.Start();
            ////WaitCallback async = new WaitCallback(PromptAlertMethod);
            ////ThreadPool.QueueUserWorkItem(async, null);

            //Thread t = new Thread(new ThreadStart(PromptAlertMethod));
            //t.Start();

            //FunDelegate funDelegate = new FunDelegate(PromptAlertMethod);

            ///*========================================================
            // * 使用this.BeginInvoke方法
            // * （也可以使用this.Invoke()方法）
            //========================================================*/

            //// this.BeginInvoke(被调用的方法的委托，要传递的参数[Object数组])
            //IAsyncResult aResult = this.BeginInvoke(funDelegate, null);

            //// 用于等待异步操作完成(-1表示无限期等待)
            //aResult.AsyncWaitHandle.WaitOne(-1);

            //// 使用this.EndInvoke方法获得返回值
            //string str = (string)this.EndInvoke(aResult);
            //MessageBox.Show(str.ToString());



            //this.BeginInvoke(

            PromptAlertMethod();

            #endregion



            #region ManualSendAcrarsAlert
            ManualSendAcrarsAlertMethod();
            #endregion

            #region ManualSendSMSAlert
            ManualSendSMSAlertMethod();

            #endregion


        }

        /// <summary>
        /// 处理席位的委托关系
        /// </summary>
        /// <param name="DelegateSeats"></param>

        private List<Guid> ExistRelationIDs;
        private void ValidateDelegateSeats(List<Model.SeatRelation> DelegateSeats)
        {
            if (DelegateSeats == null)
            {
                return;
            }

            //有请求到本席位的委托
            var itemsApply = DelegateSeats.Where(f => (f.SelfSeatID == AuthContext.Current.SelfSeat.SeatID) && (f.ConfirmStatus == 0) && (!ExistRelationIDs.Contains(f.RelationID)));

            if (itemsApply != null && itemsApply.Count() > 0)
            {
                foreach (var item in itemsApply)
                {
                    string msg = string.Format(UnConfimFormat, item.ApplyUserName, item.DelegateSeatName);
                    DelegateMessageShow messageBox = new DelegateMessageShow(msg, true, "同意", item.RelationID, true, "拒绝", false, "");
                    messageBox.Show(this);

                    ExistRelationIDs.Add(item.RelationID);
                }
            }

            //发送到别的席位的委托请求的回应
            var itemsConfirm = DelegateSeats.Where(f => (f.DelegateSeatID == AuthContext.Current.SelfSeat.SeatID) && (!ExistRelationIDs.Contains(f.RelationID)) && ((f.ConfirmStatus == 1) || (f.ConfirmStatus == 2)));

            if (itemsConfirm != null && itemsConfirm.Count() > 0)
            {
                foreach (var item in itemsConfirm)
                {
                    string msg = string.Format(item.ConfirmStatus == 1 ? AgreeFormat : RejectFormat, item.SelfSeatName);

                    DelegateMessageShow messageBox = new DelegateMessageShow(msg, false, "", "", false, "", true, "确定");

                    messageBox.Show(this);

                    ExistRelationIDs.Add(item.RelationID);
                }
            }

            //已经确定委托关系的席位
            var itemsConfirmed = DelegateSeats.Where(f => (f.SelfSeatID == AuthContext.Current.SelfSeat.SeatID) && (f.ConfirmStatus == 3));
            if (itemsConfirmed != null)
            {
                //  Guid[] delegateIDs = itemsConfirmed.ToDictionary<Model.SeatRelation, Guid>(f => f.DelegateSeatID).Keys.ToArray();
                Guid[] delegateIDs = itemsConfirmed.Select(f => f.DelegateSeatID).ToArray();

                //已解除的委托关系,提示委托席位
                var items = AuthContext.Current.DeletegateSeats.Where(f => (!delegateIDs.Contains(f.SeatID)));

                if (items != null && items.Count() > 0)
                {
                    foreach (var item in items)
                    {
                        string msg = string.Format(UnDelegateFormat, item.SeatName);
                        DelegateMessageShow messageBox = new DelegateMessageShow(msg, false, "", "", false, "", true, "确定");
                        messageBox.Show(this);
                    }
                }

                //更新委托席位
                AuthContext.Current.Credentials.RemoveAll(f => f.CredentialType == CredentialType.Delegate);

                foreach (var item in itemsConfirmed)
                {
                    Service.Seat seat = new Service.Seat();

                    seat.SeatID = item.DelegateSeatID;
                    seat.SeatName = item.DelegateSeatName;

                    Credential cdt = new Credential(seat, CredentialType.Delegate);

                    AuthContext.Current.Credentials.Add(cdt);
                }
            }
            else
            {
                AuthContext.Current.Credentials.RemoveAll(f => f.CredentialType == CredentialType.Delegate);
            }

            //更新状态栏文本
            UpdateStatusbarText();
        }

        void service_GetJsonAlerMessageCompleted(object sender, GetJsonAlerMessageBySeatListCompletedEventArgs e)
        {
            lock (locker)
            {
                if (e.Error != null)
                {
                    setTxt("系统发生错误，请检查网络链接：" + e.Error.Message, Color.Red);
                    return;
                }
                string jsonStr = e.Result;

                HandleJsonResult(jsonStr);

                timerMainTask.Enabled = true;
            }
        }

        private void ValidateLoginStatus(List<SeatLogin> loginList)
        {
            if (loginList == null)
            {
                if (!IsExists)
                {
                    IsExists = true;
                    if (DialogResult.OK == MessageBox.Show("当前用户已在别的席位登陆,你被迫登出"))
                    {
                        IsExists = false;
                        Application.Restart();
                    }
                }
            }
            else
            {
                var item = loginList.Where(f => f.UserID == AuthContext.Current.User.UserID);
                if (item == null || item.Count() == 0 || item.ToList()[0].IsLogout == true)
                {
                    if (!IsExists)
                    {
                        IsExists = true;
                        if (DialogResult.OK == MessageBox.Show("当前用户已在别的席位登陆,你被迫登出"))
                        {
                            IsExists = false;
                            Application.Restart();
                        }
                    }
                }
            }
        }

        private void InsertAlertMsgTextToControl(List<NormalAlertInfo> displayNewAlertInfos)
        {
            if (displayNewAlertInfos == null || displayNewAlertInfos.Count == 0) return;
            string dispTxt = "";
            foreach (NormalAlertInfo n in displayNewAlertInfos)
            {
                dispTxt = string.Format(n.RealDeptTime == null ? WarnFormatEst : WarnFormatReal
                    //, n.WarnTime.ToString("yyyy-MM-dd HH:mm")
                   , DateTime.Now.ToString("yyyy-MM-dd HH:mm")
                   , n.AirportFullName
                   , n.Carrier
                   , n.FlightNo
                   , GetCode4ByCode3(n.DeptAirport)
                   , GetCode4ByCode3(n.ArrAirport)
                   , n.MessageBody
                   , GetAlertActionNameByFlag(n.AlertActionFlag)
                   , n.WarnLevelName
                   , n.AirportRelation
                   , n.RealDeptTime == null ? n.EstDeptTime : n.RealDeptTime);

                Action<string, Color> satxt = new Action<string, Color>(setTxt);



                richAlertMsg.Invoke(satxt, new object[] { dispTxt, GetColorByWarnLevel(n.WarnLevel) });
            }
            List<NormalAlertInfo> lst = displayNewAlertInfos.Where<NormalAlertInfo>(s => s.AlertActionFlag == (int)(Enums.AlertActionFlag.AutoSendAcarsAlert | Enums.AlertActionFlag.ConfirmAcars)).ToList<NormalAlertInfo>();
            if (lst != null && lst.Count > 0)
            {
                string[] strarr = new string[lst.Count];
                for (int p = 0; p < lst.Count; p++)
                {
                    strarr[p] = lst[p].AlertID.ToString();
                }

                service.UpdateAlertStatus(strarr, (int)Enums.AlertActionFlag.ConfirmAcars, service.DASoapHeaderValue.UserId);

                //foreach (NormalAlertInfo norm in lst)
                //{
                //    SysGlobal.oldNormalAlertInfoList.Remove(norm);
                //}

            }
        }
        private Color GetColorByWarnLevel(int WarnLevel)
        {
            Color color = new Color();
            switch (WarnLevel)
            {
                case (int)Enums.AlertLevel.Red:
                    color = Color.Red;
                    break;
                case (int)Enums.AlertLevel.Yellow:
                    color = Color.Orange;
                    break;

                case (int)Enums.AlertLevel.Blue:
                    color = Color.Blue;
                    break;
                default:
                    break;
            }

            return color;
        }
        private void InsertAlertSMSMsgTextToControl(List<SMSAlertAllInfo> displayNewAlertSMSInfos)
        {
            if (displayNewAlertSMSInfos == null || displayNewAlertSMSInfos.Count == 0) return;
            string dispTxt = "";
            string[] strarr = new string[displayNewAlertSMSInfos.Count];
            int i = 0;
            foreach (SMSAlertAllInfo n in displayNewAlertSMSInfos)
            {
                strarr[i] = n.SMSAlertID.ToString();
                i++;
                dispTxt = string.Format(SMSWarnFormat
                           , DateTime.Now.ToString("yyyy-MM-dd HH:mm")
                           , GetAlertActionNameByFlag(n.AlertActionFlag)
                           , n.AirportFullName
                           , n.WarnLevelName
                           , n.FlightCount.ToString()
                           , n.MessageBody);


                Action<string, Color> satxt = new Action<string, Color>(setTxt);
                richAlertMsg.Invoke(satxt, new object[] { dispTxt, GetColorByWarnLevel(n.WarnLevel) });
            }
            List<SMSAlertAllInfo> lst = displayNewAlertSMSInfos.Where<SMSAlertAllInfo>(s => s.AlertActionFlag == (int)(Enums.AlertActionFlag.AutoSendSMSAlert | Enums.AlertActionFlag.ConfirmSMS)).ToList<SMSAlertAllInfo>();
            if (lst != null && lst.Count > 0)
            {
                strarr = new string[lst.Count];
                for (int p = 0; p < lst.Count; p++)
                {
                    strarr[p] = lst[p].SMSAlertID.ToString();
                }
                service.UpdateSMSAlertStatus(strarr, (int)Enums.AlertActionFlag.ConfirmSMS, service.DASoapHeaderValue.UserId);
                //foreach (SMSAlertAllInfo norm in lst)
                //{
                //    SysGlobal.oldSMSAlertAllInfoList.Remove(norm);
                //}

            }
        }

        private List<NormalAlertInfo> getNewAlertInfos(List<NormalAlertInfo> oldLst, List<NormalAlertInfo> newLst)
        {
            List<NormalAlertInfo> lst = new List<NormalAlertInfo>();

            foreach (NormalAlertInfo newO in newLst)
            {
                bool flag = false;
                foreach (NormalAlertInfo oldO in oldLst)
                {
                    if (newO.AlertID == oldO.AlertID) { flag = true; break; }
                }

                if (!flag) lst.Add(newO);
            }

            return lst;
        }

        private List<SMSAlertAllInfo> getNewAlertSMSInfos(List<SMSAlertAllInfo> oldLst, List<SMSAlertAllInfo> newLst)
        {
            List<SMSAlertAllInfo> lst = new List<SMSAlertAllInfo>();

            foreach (SMSAlertAllInfo newO in newLst)
            {
                bool flag = false;
                foreach (SMSAlertAllInfo oldO in oldLst)
                {
                    if (newO.SMSAlertID == oldO.SMSAlertID) { flag = true; break; }
                }

                if (!flag) lst.Add(newO);
            }

            return lst;
        }

        private void setTxt(string text, Color color)
        {

            //richAlertMsg.ForeColor = color;
            //richAlertMsg.Font = new Font("Microsoft Sans Serif", 11, FontStyle.Bold);
            //richAlertMsg.AppendText(text + "\n\n");
            //text = text + "\n\n";
            this.richAlertMsg.AppendText(text);
            this.richAlertMsg.Select(richAlertMsg.TextLength - text.Length, text.Length);
            this.richAlertMsg.SelectionFont = new Font("Microsoft Sans Serif", 11, FontStyle.Bold);
            this.richAlertMsg.SelectionColor = color;
            this.richAlertMsg.AppendText("\n\n");
        }

        private void UpdateStatusbarText()
        {
            try
            {
                string message = "  代理的席位: ";
                if (AuthContext.Current.DeletegateSeats == null || AuthContext.Current.DeletegateSeats.Count == 0)
                {
                    message = "";
                }
                else
                {
                    foreach (Credential st in AuthContext.Current.DeletegateSeats)
                    {
                        message += st.SeatName + ",";
                    }
                }
                ((frmMain)this.Parent.Parent.Parent).tssDelegateSeats.Text = message.TrimEnd(',');
            }
            catch
            {
                return;
            }
        }

        #endregion

        #region Event Handlers

        private void timerMainTask_Tick(object sender, EventArgs e)
        {
            DisposeMessagerGetter();
        }

        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            DisposeMessagerGetter();
            //Thread th = new Thread(new ThreadStart(disposeeee));
            //th.Start();


            //WaitForm wf = new WaitForm();
            //wff = (((DispatchAssist.AppHost.frmMain)(this.Parent.Parent.Parent))).wwf;

            //wff.StartPosition = FormStartPosition.CenterParent;
            ////wff = wff;
            //timer1.Interval = 1;

            //timer1.Enabled = true;
            //(((DispatchAssist.AppHost.frmMain)(this.Parent.Parent.Parent))).wwf.TopMost = true;
            //(((DispatchAssist.AppHost.frmMain)(this.Parent.Parent.Parent))).wwf.ShowDialog();
        }


        //private void disposeeee(WaitForm wf)
        //{
        //    //Thread.Sleep(1000);


        //    //List<frmPromptAlert> lst = new List<frmPromptAlert>();
        //    for (int i = 0; i < 200; i++)
        //    {



        //        frmPromptAlert frm = new frmPromptAlert();

        //        //lst.Add(frm);
        //        //for (int i = 499; i >= 0; i--)
        //        //{
        //        //    frm.panelPrompt.Controls.Add(new ucPromptAlert(new NormalAlertInfo(), i--) { Dock = DockStyle.Top });
        //        //}
        //        frm.Show();

        //    }
        //    wf.Close();
        //    //for (int i = 0; i < lst.Count; i++)
        //    //{
        //    //    lst[i].Visible = true;

        //    //}


        //    timer1.Enabled = false;
        //}

        private void timerMonitor_Tick(object sender, EventArgs e)
        {
            //if (!CommonFunM()) { timerMonitor.Enabled = false; MessageBox.Show("处理完成！"); }
        }

        public bool CommonFunM()
        {
            if ((AlertContext.Dic_Dispose_Acars != null && AlertContext.Dic_Dispose_Acars.Count > 0) || (AlertContext.Dic_Dispose_Bubble != null && AlertContext.Dic_Dispose_Bubble.Count > 0) || (AlertContext.Dic_Dispose_Prompt != null && AlertContext.Dic_Dispose_Prompt.Count > 0) || (AlertContext.Dic_Dispose_Sms != null && AlertContext.Dic_Dispose_Sms.Count > 0))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //disposeeee((((DispatchAssist.AppHost.frmMain)(this.Parent.Parent.Parent))).wwf);
        }

        private void timPromptAlert_Tick(object sender, EventArgs e)
        {
            if (AlertContext.Dic_Prompt_List.Count > 0)
            {
                //wff.Close();

                List<frmPromptAlert> list = new List<frmPromptAlert>();

                list.AddRange(AlertContext.Dic_Prompt_List);
                AlertContext.Dic_Prompt_List.Clear();
                Action<frmPromptAlert> funDelegate;



                foreach (frmPromptAlert frm in list)
                {
                    //if (!frm.InvokeRequired)
                    //{
                    //    //frm.Enabled = false;

                    //    funDelegate = new Action<frmPromptAlert>(FrmShow);
                    //    IAsyncResult aResult = funDelegate.BeginInvoke(frm, callbackshow, frm);
                    //    //frm.Visible = false;
                    //    frm.Enabled = true;
                    //}

                    frm.Show();
                    //frm.ShowDialog();

                    //frm.Refresh();
                }


            }
        }

        private void FrmShow(frmPromptAlert frm)
        {

            frm.ShowDialog();

        }
        private void callbackshow(IAsyncResult result)
        {

            if (result.IsCompleted)
            {
                lock (locker)
                {
                    ((frmPromptAlert)result.AsyncState).Enabled = true;

                    //((frmPromptAlert)result.AsyncState).Enabled = true;
                }
            }
        }

        private void timManualSendAcrarsAlert_Tick(object sender, EventArgs e)
        {
            if (AlertContext.Dic_Acars_List.Count > 0)
            {
                // wff.Close();

                List<frmManualSendAcrarsAlert> list = new List<frmManualSendAcrarsAlert>();

                list.AddRange(AlertContext.Dic_Acars_List);
                AlertContext.Dic_Acars_List.Clear();
                foreach (frmManualSendAcrarsAlert frm in list)
                {

                    frm.Show();

                }


            }
        }

        private void timManualSendSMSAlert_Tick(object sender, EventArgs e)
        {
            if (AlertContext.Dic_SMS_List.Count > 0)
            {
                //wff.Close();

                List<frmManualSendSMSAlert> list = new List<frmManualSendSMSAlert>();

                list.AddRange(AlertContext.Dic_SMS_List);
                AlertContext.Dic_SMS_List.Clear();
                foreach (frmManualSendSMSAlert frm in list)
                {

                    frm.Show();

                }


            }
        }

        #region Old
        //        private void button1_Click(object sender, EventArgs e)
        //        {

        //            frmPromptAlert frm = new frmPromptAlert();

        //            for (int i = 0; i < 10; i++)
        //            {
        //                ucPromptAlert uc = new ucPromptAlert();
        //                uc.Dock = DockStyle.Top;

        //                frm.panelPrompt.Controls.Add(uc);
        //                //frm.panelPrompt.Controls.Add(uc2);
        //                //frm.panelPrompt.Controls.Add(uc3);
        //            }
        //            frm.ShowDialog();
        //            //WF mh1 = new WF();
        //            //mh1.Show();
        //        }

        //        private void button4_Click(object sender, EventArgs e)
        //        {

        //            ClientMessageInfo cminfo = clientMInfo.GetAlertMessageByAlertAction((int)Enums.AlertActionFlag.ManualSendSMSAlert);
        //            if (cminfo.SMSAlertList == null || cminfo.SMSAlertList.Count == 0) return;

        //            foreach (SMSAlertAllInfo smsAlertInfo in cminfo.SMSAlertList)
        //            {
        //                frmManualSendSMSAlert frm = new frmManualSendSMSAlert(smsAlertInfo);
        //                frm.Show();
        //            }
        //        }

        //        private void button3_Click(object sender, EventArgs e)
        //        {
        //            //ClientMessageInfo cminfo = clientMInfo.GetAlertMessageByAlertAction((int)Enums.AlertActionFlag.ManualSendAcrarsAlert);
        //            //if (cminfo.NormalAlertList == null || cminfo.NormalAlertList.Count == 0) return;
        //            //foreach (NormalAlertInfo nainfo in cminfo.NormalAlertList)
        //            //{
        //            //    frmManualSendAcrarsAlert frm = new frmManualSendAcrarsAlert(nainfo);
        //            //    frm.Show();
        //            //}
        //            for (int i = 0; i < 50; i++)
        //            {
        //                frmManualSendAcrarsAlert frm = new frmManualSendAcrarsAlert();
        //                frm.Show();
        //            }

        //        }

        //        private void button2_Click(object sender, EventArgs e)
        //        {
        //            string seatid = service.DASoapHeaderValue.SeatId[0];
        //            //ClientMessageInfo cminfo = clientMInfo.GetAlertMessageByAlertAction((int)Enums.AlertActionFlag.BubbleAlert);
        //            //if (cminfo.NormalAlertList == null || cminfo.NormalAlertList.Count == 0) return;
        //            //ucBubbleAlert uc = new ucBubbleAlert(cminfo.NormalAlertList);

        //            frmBubbleAlert bf = new frmBubbleAlert(@"dddddddddddddddddddddddddddddddddddddddddddddddddddd
        //ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
        //dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
        //dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd");

        //            //frmBubbleAlert.WidthMax = 500;
        //            //frmBubbleAlert.HeightMax = 400;

        //            bf.ScrollShow();
        //        }
        #endregion
    }
}
